package com.google.code.whitetask.old;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TryCatchDecorator extends AbstractFluentTask {
  private static final Log LOG = LogFactory.getLog(TryCatchDecorator.class);
  static final TaskResultType DEFAULT_RESULT_WHEN_FAILED = TaskResultType.FAILURE;
  static final boolean DEFAULT_LOGGABLE = true;
  static final boolean DEFAULT_THROWABLE = false;

  private Task task;
  private boolean loggable = DEFAULT_LOGGABLE;
  private boolean throwable = DEFAULT_THROWABLE;
  private TaskResultType resultToReturn = DEFAULT_RESULT_WHEN_FAILED;

  public TryCatchDecorator(Task task) {
    this.task = task;
  }

  public TryCatchDecorator loggable(boolean loggable) {
    this.loggable = loggable;
    return this;
  }

  public TryCatchDecorator throwable(boolean throwable) {
    this.throwable = throwable;
    return this;
  }

  public TryCatchDecorator willReturn(TaskResultType result) {
    this.resultToReturn = result;
    return this;
  }

  public TaskResultType execute(TaskContext context) {
    try {
      return task.execute(context);
    } catch (Exception e) {
      if (loggable) {
        LOG.error(e, e);
      }
      if (throwable) {
        throw new FailedTaskException(e.toString(), e);
      }
      return resultToReturn;
    }
  }

  Task getTask() {
    return task;
  }

  boolean isLoggable() {
    return loggable;
  }

  boolean isThrowable() {
    return throwable;
  }

  TaskResultType getResultWhenFailed() {
    return resultToReturn;
  }
}
